<template>
	<div class="root">
    <NoteHeader :addTodo='addTodo'/>
    <NoteList :todos='todos'/>  
    <NoteFooter :todos='todos' :checkAllTodo='checkAllTodo' :clear='clearAllTodo'/>
	</div>

</template>

<script>
import NoteHeader from './components/NoteHeader.vue'
import NoteList from './components/NoteList.vue'
import NoteFooter from './components/NoteFooter.vue'


export default {
	name:'App',
  components:{NoteHeader,NoteList,NoteFooter},
  data() {
    return {
      todos:JSON.parse(localStorage.getItem('todos')) || []
    }
  },
  methods:{
    addTodo(todoObj){
      this.todos.unshift(todoObj)
    },
    checkTodo(id){
      this.todos.forEach((todo)=>{
        if(todo.id==id) todo.done = !todo.done
      })
    },
    deleteTodo(id){
      this.todos=this.todos.filter(todo => todo.id !== id)
    },
    checkAllTodo(done){
      this.todos.forEach((todo)=>{
        todo.done=done
      })
    },
    clearAllTodo(){
      this.todos=this.todos.filter((todo)=>{
        return !todo.done
      })
    }
  },

  watch:{
    todos:{
      deep:true,
      handler(newValue){
        localStorage.setItem('todos',JSON.stringify(newValue))
      }
    }
  },

  mounted() {
    this.$bus.$on('checkTodo',this.checkTodo)
    this.$bus.$on('deleteTodo',this.deleteTodo)

  },
  beforeDestroy(){
    this.$bus.$off('checkTodo')
    this.$bus.$off('deleteTodo')
  }
}
</script>

<style scoped>
.root {
  width: 500px;
  border: 1px solid #ccc;
  margin: auto;
}

</style>